/* 
 * Copyright 2011 kOSMik.
 * This file is part of kOSMik.
 * 
 * kOSMik is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * kOSMik is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with kOSMik.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * kOSMik:
 * Open Street Map - Editor.
 * http://code.google.com/p/swp-dv-ws2010-osm-2/
 */

package de.fuberlin.kosmik.gui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import de.fuberlin.kosmik.R;
import de.fuberlin.kosmik.data.osmt.OsmtElementRecord;
import de.fuberlin.kosmik.data.osmt.OsmtFeatureRecord;
import de.fuberlin.kosmik.data.osmt.OsmtNodeRecord;
import de.fuberlin.kosmik.gui.view.adapter.TagSearchAdapter;
import de.fuberlin.kosmik.gui.view.adapter.TagSearchAdapter.TagListItem;
import de.fuberlin.kosmik.gui.view.adapter.ViewHolder;
import de.fuberlin.kosmik.log.Constants;

/**
 * This activity allows the user to search for tags (features, bundles and
 * themes) of a specific type of element (poi, way, area)
 * <p>
 * The extra bundle of the intent defines with the key KEY_TABLE_FILTER which
 * tables should be queried (TABLE_FILTER_ALL, TABLE_FILTER_FEATURES...) and
 * with the key KEY_ELEMENT_FILTER which elements should be shown. The values of
 * the second key are stored in {@link TagSearchAdapter.ItemType}. If the Intent
 * has no extra bundle, all tables will be queried and all items will be shown.
 * 
 * @author micha
 * 
 */
public class TagSearchActivity extends Activity implements OnClickListener, OnItemClickListener {
	/**
	 * Bundle key indicates what tables should queried.
	 */
	public static final String KEY_ELEMENT_FILTER = "element_filter";

	/**
	 * Bundle key indicates what tables should queried.
	 */
	public static final String KEY_TABLE_FILTER = "table_filter";
	/**
	 * Bundle tag signals that all tables should queried.
	 */
	public static final byte TABLE_FILTER_ALL = 1;
	/**
	 * Bundle tag signals that only the feature table should queried.
	 */
	public static final byte TABLE_FILTER_FEATURES = 2;
	/**
	 * Bundle tag signals that only the bundle table should queried.
	 */
	public static final byte TABLE_FILTER_BUNDLES = 4;
	/**
	 * Bundle tag signals that only the theme table should queried.
	 */
	public static final byte TABLE_FILTER_THEMES = 16;

	private ListView lstTags;
	private ImageButton btnSearch;
	/**
	 * Reference to the search box in the action bar.
	 */
	private EditText actionBarSearchBox;
	/**
	 * Reference to the tagAdapter which contains and shows all results.
	 */
	private TagSearchAdapter tagAdapter;

	private int elementFilter;

	private static final int BUNDLE_REQUEST_CODE = 1;
	private static final int TAGPICKER_REQUEST_CODE = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tag_search);

		Intent intent = getIntent();
		byte tableFilter = intent.getByteExtra(KEY_TABLE_FILTER, TABLE_FILTER_ALL);
		elementFilter = intent.getIntExtra(KEY_ELEMENT_FILTER, OsmtElementRecord.ELEMENT_ALL);
		tagAdapter = new TagSearchAdapter(this, tableFilter, elementFilter);
		findViews();
		lstTags.setAdapter(tagAdapter);
		lstTags.setOnItemClickListener(this);
		registerForContextMenu(lstTags);
	}

	private void findViews() {
		lstTags = (ListView) findViewById(R.id.listTags);
		btnSearch = (ImageButton) findViewById(R.id.action_bar_search_button);
		actionBarSearchBox = (EditText) findViewById(R.id.action_bar_search_box);
		btnSearch.setOnClickListener(this);
		actionBarSearchBox.addTextChangedListener(tagAdapter);
	}

	@Override
	public void onClick(View view) {
		/*
		 * if (view.getId() == R.id.action_bar_search_button) { // Search Button
		 * pressed }
		 */
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View itemView, int position, long id) {
		ViewHolder<TagListItem> viewHolder = (ViewHolder<TagListItem>) itemView.getTag();
		if (!viewHolder.isHeader()) {
			TagListItem item = viewHolder.getItem();
			if (item.item_type == TagSearchAdapter.ItemType.BUNDLE_ITEM) {
				startBundleActivity((OsmtNodeRecord) item.osmtElement);
			} else if (item.item_type == TagSearchAdapter.ItemType.THEME_ITEM) {
				startTagPickerActivity((OsmtNodeRecord) item.osmtElement);
			} else if (item.item_type == TagSearchAdapter.ItemType.FEATURE_ITEM) {
				startBundleActivityWithFeature((OsmtFeatureRecord) item.osmtElement);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		setResult(resultCode, data);
		finish();
	}

	/**
	 * Called, when the context menu pop up.
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
		Log.d(Constants.TAG, "ContextMenu" + view);
		if (view == lstTags) {

			// get the view of the item that the event occur
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			View itemView = info.targetView;
			ViewHolder<TagListItem> viewHolder = (ViewHolder<TagListItem>) itemView.getTag();
			// check if the clicked view is a item and no header
			Log.d(Constants.TAG, "List" + viewHolder.isHeader());
			if (!viewHolder.isHeader()) {
				showDialog(viewHolder.getItem());
			}

		}
	}

	private void showDialog(TagListItem listItem) {
		OsmtElementRecord elementRecord = listItem.osmtElement;
		Log.d(Constants.TAG, "showDialog");
		if (elementRecord.comment != null && !elementRecord.comment.equals("")) {
			Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.tag_search_dialog);
			dialog.setTitle(elementRecord.toString());

			TextView comment = (TextView) dialog.findViewById(R.id.tag_search_dialog_comment);
			comment.setText(elementRecord.comment);

			if (listItem.item_type == TagSearchAdapter.ItemType.BUNDLE_ITEM) {
				OsmtNodeRecord osmtNodeRecord = (OsmtNodeRecord) elementRecord;
				if (osmtNodeRecord.wiki != null) {
					TextView wikiLink = (TextView) dialog
							.findViewById(R.id.tag_search_dialog_wiki);
					wikiLink.setText(Html.fromHtml("<a href=\"" + osmtNodeRecord.wiki + "\";>"
							+ osmtNodeRecord.wiki + "</a>"));
					wikiLink.setMovementMethod(LinkMovementMethod.getInstance());
				}
			} else if (listItem.item_type == TagSearchAdapter.ItemType.FEATURE_ITEM) {
				OsmtFeatureRecord osmtFeatureRecord = (OsmtFeatureRecord) elementRecord;
				if (osmtFeatureRecord.wiki != null) {
					TextView wikiLink = (TextView) dialog
							.findViewById(R.id.tag_search_dialog_wiki);
					wikiLink.setText(Html.fromHtml("<a href=\"" + osmtFeatureRecord.wiki
							+ "\";>" + osmtFeatureRecord.wiki + "</a>"));
					wikiLink.setMovementMethod(LinkMovementMethod.getInstance());
				}
			}

			dialog.show();
		} else {
			Toast.makeText(this, this.getString(R.string.tagsearch__no_comment),
					Toast.LENGTH_SHORT).show();
		}

	}

	// starts BundleActivity with the id of the given BundleReocord
	private void startBundleActivity(OsmtNodeRecord bundleRecord) {
		int bundleId = bundleRecord.id;
		Intent bundleIntent = new Intent(this, TagBundleActivity.class);
		bundleIntent.putExtra("OSM_BUNDLE_ID", bundleId);
		startActivityForResult(bundleIntent, BUNDLE_REQUEST_CODE);
	}

	// starts TagPickerActivity to show all bundles that belong to the given
	// theme
	private void startTagPickerActivity(OsmtNodeRecord osmtElement) {
		Intent childNodeIntent = new Intent(this, TagPickerActivity.class);
		childNodeIntent.putExtra("TITLE", osmtElement.displayName);
		childNodeIntent.putExtra("OSM_ELEMENT_FILTER", elementFilter);
		childNodeIntent.putExtra("OSM_PARENT_NODE_ID", osmtElement.id);
		startActivityForResult(childNodeIntent, TAGPICKER_REQUEST_CODE);
	}

	// starts BundleActivity with a given Feature
	private void startBundleActivityWithFeature(OsmtFeatureRecord osmtElement) {
		final Intent intent = new Intent(this, TagBundleActivity.class);
		Bundle featureBundle = new Bundle();
		featureBundle.putString(osmtElement.osmKey, osmtElement.osmValue);
		intent.putExtra("OSM_FEATURE_BUNDLE", featureBundle);
		startActivityForResult(intent, BUNDLE_REQUEST_CODE);
	}

}
